package com.hmdp.service.impl;

import cn.hutool.core.lang.Holder;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService iSeckillVoucherService;

    @Resource
    private IVoucherOrderService iVoucherOrderService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 1. 查询优惠卷
        SeckillVoucher voucher = iSeckillVoucherService.getById(voucherId);
        // 2. 查询秒杀是否开始
        if(voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始");
        }
        // 3. 查询秒杀是否结束
        if(voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束");
        }

        Long userId = UserHolder.getUser().getId();
        // 分布式锁
        SimpleRedisLock lock = new SimpleRedisLock(this.stringRedisTemplate, userId.toString());
        boolean success = lock.tryLock(100L);
        if(!success) {
            return Result.fail("不允许重复下单");
        }
        try {
            return iVoucherOrderService.createOrder(voucher);
        } finally {
            lock.unlock();
        }

        // 单机锁
        // synchronized (userId.toString().intern()) {
        //     return iVoucherOrderService.createOrder(voucher);
        // }
    }

    @Transactional
    public Result createOrder(SeckillVoucher voucher) {
        // 4. 判断库存是否充足
        if(voucher.getStock() < 1) {
            return Result.fail("库存不足");
        }

        // 5. 查询这个人下单了吗
        Long voucherId = voucher.getVoucherId();
        Long user_id = UserHolder.getUser().getId();
        LambdaUpdateWrapper<VoucherOrder> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(VoucherOrder::getVoucherId, voucherId);
        wrapper.eq(VoucherOrder::getUserId, user_id);
        int count = this.count(wrapper);
        if(count > 0) {
            return Result.fail("已经使用过优惠卷了");
        }

        // 6. 扣减库存
        // LambdaUpdateWrapper<SeckillVoucher> wrapper = new LambdaUpdateWrapper<>();
        // wrapper.eq(SeckillVoucher::getVoucherId, voucherId);
        // wrapper.eq(SeckillVoucher::getStock, voucher.getStock());
        // wrapper.set(SeckillVoucher::getStock, voucher.getStock() - 1);
        // boolean success = iSeckillVoucherService.update(wrapper);

        LambdaUpdateWrapper<SeckillVoucher> s_wrapper = new LambdaUpdateWrapper<>();
        s_wrapper.eq(SeckillVoucher::getVoucherId, voucherId);
        s_wrapper.gt(SeckillVoucher::getStock, 0);
        s_wrapper.setSql("stock = stock - 1");
        boolean success = iSeckillVoucherService.update(s_wrapper);
        if(!success) {
            return Result.fail("库存不足");
        }
        // 7. 创建订单
        VoucherOrder order = new VoucherOrder();
        // 订单id，用户id,代金卷id
        long orderId = redisIdWorker.nextId("order");
        order.setId(orderId);
        order.setVoucherId(voucherId);
        order.setUserId(UserHolder.getUser().getId());
        iVoucherOrderService.save(order);
        return Result.ok(orderId);
    }
}
